import React, { useEffect, useState } from 'react';
import { Modal, Result, Button, message } from 'antd';
import { connect, history } from 'umi';
import { SmileOutlined } from '@ant-design/icons';
import styles from './index.less';
import { getQuestionType } from './service';

const Attempt = function ({ dispatch, currentUser }) {
  const [modalVisble, setModalVisble] = useState<boolean>(false);

  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [typeList, setTypeList] = useState<[]>([]);
  const [detailSource, setDetailSource] = useState<{}>({});
  const [isShowAttempt, setIsShowAttempt] = useState<number>(currentUser.tryOutSwitch);
  const [isNoData, setIsNoData] = useState<number>(0);

  console.log('currentUser', currentUser);

  const firstNotice = () => {
    const tryNotice = localStorage.getItem('tryNotice');
    if (!tryNotice) {
      setModalVisble(true);
      localStorage.setItem('tryNotice', true);
    }
  };

  const getTypeList = async () => {
    const { phone } = currentUser;
    const { code, data, info } = await getQuestionType({ phone });

    if (code != 0) {
      message.error(info);
      return;
    }

    if (!data.tryOutSwitch) {
      message.info('抱歉，试稿功能暂时关闭，待管理员通知');
    }

    if (!data || data.list.length <= 0) {
      setIsNoData(1);
    }

    setIsShowAttempt(data.tryOutSwitch);
    setTypeList(data.list);
  };

  useEffect(() => {
    if (isShowAttempt) {
      getTypeList();
      firstNotice();
    }
  }, []);

  const Detail = () => {
    return (
      <>
        <div className={styles['detail-state']}>
          <div>
            状态：
            <span className={styles['detail-state-error']}>
              {detailSource.status === 0 && '待审核'}
              {detailSource.status === 1 && '已通过'}
              {detailSource.status === 2 && '未通过'}
              {detailSource.remark ? `(${detailSource.remark})` : ''}
            </span>
          </div>
          <div>
            回复时间：
            <span className={styles['detail-state-error']}>{detailSource.replyTime}</span>
          </div>
        </div>

        {/* <QuestionMsg showNextBtn={false} source={detailSource} /> */}
        <p className={styles['detail-title']}>{detailSource.title}</p>

        <div className={styles['detail-reply-view']}>
          {detailSource.content && (
            <p
              className={styles['detail-text']}
              dangerouslySetInnerHTML={{ __html: detailSource.content }}
            />
          )}
        </div>
      </>
    );
  };

  const toggleDetail = (item) => {
    setDetailModalVisible(true);
    console.log('1111', item);
    if (item.questionInfo.status === 4) {
      dispatch({
        type: 'attempt/saveInfo',
        payload: item,
      });
      history.push('/produce/attemptAnswer');
      return;
    }

    setDetailSource(item.questionInfo);
  };

  const AttemptContent = () => {
    return (
      <>
        <div className={styles.cardBox}>
          {!isNoData ? (
            typeList.length > 0 &&
            typeList.map((item, index) => {
              if (item.questionInfo.status === 3) return null;

              return (
                <div
                  className={styles.cardUnit}
                  key={index}
                  onClick={() => {
                    toggleDetail(item);
                  }}
                >
                  <span>{item.questionInfo.type}</span>
                  {item.questionInfo.status === 0 && (
                    <span className={styles['label-audit']}>待审核</span>
                  )}
                  {item.questionInfo.status === 1 && (
                    <span className={styles['label-pass']}>已通过</span>
                  )}
                  {item.questionInfo.status === 2 && (
                    <span className={styles['label-nopass']}>未通过</span>
                  )}
                  {item.questionInfo.status === 4 && (
                    <span className={styles['label-try']}>去试稿&gt;&gt;</span>
                  )}
                </div>
              );
            })
          ) : (
            <div className={styles['nodata-box']}>
              <Result icon={<SmileOutlined />} title="暂时没有试题" />
            </div>
          )}
        </div>
        <Modal
          title="试稿须知"
          width={600}
          visible={modalVisble}
          okText="知道了"
          onOk={() => {
            setModalVisble(false);
          }}
          onCancel={() => {
            setModalVisble(false);
          }}
          footer={[
            <Button
              onClick={() => {
                setModalVisble(false);
              }}
            >
              知道了
            </Button>,
          ]}
        >
          {
            <dl>
              <dd>1.通过试稿后才能正式入驻系统参与答题；</dd>
              <dd>
                2.每个类型的题目只有1次试稿机会，答题前请认真阅读答题须知。若试稿未通过，需等待题库更新后才可再次进行试稿；
              </dd>
              <dd>3.试稿哪种类型的题目，通过后也只能答该类型的题目；</dd>
              <dd>4.题库每3~5天更新一次，每次更新所有类型的题目。</dd>
            </dl>
          }
        </Modal>

        <Modal
          title={detailSource.type}
          visible={detailModalVisible}
          onCancel={() => {
            setDetailModalVisible(false);
          }}
          width={1000}
          footer={[]}
        >
          {<Detail />}
        </Modal>
      </>
    );
  };

  return (
    <div className={styles.content}>
      {isShowAttempt ? <AttemptContent /> : <Result title="抱歉，试稿功能暂时关闭，待管理员通知" />}
    </div>
  );
};

export default connect(({ user: { currentUser } }) => ({ currentUser }))(Attempt);
